package com.atguigu.day08;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.stream.Stream;

public class Flink04_State_KeyedState_ValueState {

    public static void main(String[] args) throws Exception {

        //1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.读取数据
        DataStreamSource<String> socketTextStream = env.socketTextStream("hadoop102", 9999);

        //3.将每行数据转换为JavaBean
        SingleOutputStreamOperator<WaterSensor> waterSensorDS = socketTextStream.map(line -> {
            String[] fields = line.split(",");
            return new WaterSensor(fields[0],
                    Long.parseLong(fields[1]),
                    Double.parseDouble(fields[2]));

        });

        //4.按照传感器Id分组
        KeyedStream<WaterSensor, String> keyedStream = waterSensorDS.keyBy(WaterSensor::getId);

        //5.使用ProcessFunction实现水位线出现跳变则输出报警信息至侧输出流
        SingleOutputStreamOperator<WaterSensor> result = keyedStream.process(new KeyedProcessFunction<String, WaterSensor, WaterSensor>() {

            //定义状态
            private ValueState<Double> lastVcState;

            @Override
            public void open(Configuration parameters) throws Exception {
                //状态初始化
                lastVcState = getRuntimeContext().getState(new ValueStateDescriptor<Double>("value-state", Double.class));
            }

            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<WaterSensor> out) throws Exception {

                //获取状态中的数据
                Double lastVc = lastVcState.value();

                if (lastVc != null && Math.abs(lastVc - value.getVc()) > 10.0D) {
                    //将报警信息写入侧输出流
                    ctx.output(new OutputTag<String>("SideOutPut") {
                    }, value.getId() + "出现水位跳变！");
                }

                //将当前水位线保存至状态中
                lastVcState.update(value.getVc());

                //将数据写入主流
                out.collect(value);

            }
        });

        //6.获取侧输出流数据和主流数据并打印
        result.print("Main>>>>>>>>>>>");
        result.getSideOutput(new OutputTag<String>("SideOutPut") {
        }).print("Side>>>>>>>>>>>>>");

        //7.启动
        env.execute();

    }

}
